﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Security.Principal;
using System.Text.RegularExpressions;
using System.Collections.Specialized;
using System.Collections;
using System.IO;
using System.Web.Profile;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;

namespace EasyBuildingCMS.BLL
{
    public sealed class Helper
    {
        #region "String Helper"

        //reuse TheBeerHouse

        public static bool isInteger(string s)
        {
            try {
                Int32.Parse(s);
                return true;
                }
            catch (FormatException) {
                return false;
            }
        }

        public static int? ToInt(string s) {

            try
            {
                return Int32.Parse(s);
            }
            catch (FormatException)
            {
                return null;
            }
        }

        public static string GetVirtualHandlerNameFromURL(string url)
        {
            string urlPart = url.Substring(url.IndexOf('_')+1);
            if (urlPart==null) return "";
            return urlPart.Split('.')[0];
        }

        public static DateTime? ConvertStringToDateTime(string s)
        {
            DateTime date;


            DateTimeFormatInfo dtF = new DateTimeFormatInfo();
            dtF.FullDateTimePattern = "MM/dd/yyyy";
            dtF.ShortDatePattern = "MM/dd/yyyy";

            if (DateTime.TryParse(s.Trim(),dtF, DateTimeStyles.NoCurrentDateDefault, out date)) 
            { 
                return date; 
            } 
            else 
            { 
                return null; 
            }
        }

        public static string ConvertNullToEmptyString(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return string.Empty;
            }
            return input;
        }

        public static string GetURLPath(string vURL)
        {
            var _Regex = new Regex("://[^/]+/(?<path>[^?\\s<>#\"]+)");
            if (_Regex.Matches(vURL).Count > 0)
            {
                return _Regex.Match(vURL).Groups[1].ToString();
            }
            return vURL;
        }

        public static string ConvertToHtml(string content)
        {
            content = HttpUtility.HtmlEncode(content);
            content = content.Replace("  ", "&nbsp;&nbsp;").Replace(@"\t", "&nbsp;&nbsp;&nbsp;").Replace(@"\n", "<br>");
            return content;
        }

        public static string FilterProfanity(string vText)
        {
            var ProfanityReg = new Regex(@"\b(bad phrase)\b", RegexOptions.Multiline | RegexOptions.IgnoreCase);
            return ProfanityReg.Replace(vText, "$%^&**");
        }

        public static string FormatSpacesForURL(string vURL)
        {
            return vURL.Trim().Replace(" ", "-");
        }

         public static string ProperCase(string Text)
        {
            var objCulture = new CultureInfo("en-US");
            return objCulture.TextInfo.ToTitleCase(Text.ToLower());
        }

        /// <summary>
        /// This is a utlity function I used to wrap the Regex.Replace
        /// method. It just provides a shorthand way to do a replace.
        /// </summary>
        /// <param name="strin"></param>
        /// <param name="strExp"></param>
        /// <param name="strReplace"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static string RegexReplace(string strin, string strExp, string strReplace)
        {
            return Regex.Replace(strin, strExp, strReplace);
        }

        public static string RemoveHTML(string strText)
        {
            return RegexReplace(strText, "<[^>]*>", string.Empty);
        }

        /// <summary>
        /// Cleans the whitespace, or unneeded characters for the
        /// page to redner in the browser.
        /// </summary>
        /// <param name="strText"></param>
        /// <returns></returns>
        /// <remarks>
        /// This make the page a little thinner by not including
        /// extra characters that do not make the page render,
        /// but rather help developers manage the markup in editors.</remarks>
        public static string RemoveWhiteSpace(string strText)
        {
            return RegexReplace(strText, @"(?<=>)\s+(?=</?)", string.Empty);
        }

        public static string ResolveUrl(string originalUrl)
        {
            if (originalUrl == null)
            {
                return null;
            }
            if (originalUrl.IndexOf("://") != -1)
            {
                return originalUrl;
            }
            if (!originalUrl.StartsWith("~"))
            {
                return originalUrl;
            }
            if (HttpContext.Current == null)
            {
                throw new ArgumentException("Invalid URL: Relative URL not allowed.");
            }
            return (HttpContext.Current.Request.ApplicationPath + originalUrl.Substring(1).Replace("//", "/"));
        }

        
        public static string SEOFriendlyURL(string vURL, string vExtension)
        {
            if (!string.IsNullOrEmpty(vURL))
            {
                return ResolveUrl(vURL.Replace("#", "").Replace(" ", "-") + vExtension);
            }
            return string.Empty;
        }

        public static bool IsValidString(string vValue, int vMax)
        {
            return IsValidString(vValue, 0, vMax);
        }

        public static bool IsValidString(string vValue, int vMin, int vMax)
        {
            if (vMin > 0)
            {
                if (string.IsNullOrEmpty(vValue) && vMin <= vValue.Length)
                {
                    return false;
                }
            }
            if (vMax < vValue.Length)
            {
                return false;
            }
            return true;
        }

        #endregion

        #region "UI"

        public static int GetPageIndex(int startRowIndex, int maximumRows)
        {
            if (maximumRows <= 0)
            {
                return 0;
            }
            return (int)Math.Round(Math.Floor((double)(((double)startRowIndex) / ((double)maximumRows))));
        }

        /// <summary>
        /// Adds the onfocus and onblur attributes to all input controls found in the specified parent,
        /// to change their apperance with the control has the focus.
        /// </summary>
        /// <param name="container"></param>
        /// <param name="className"></param>
        /// <param name="onlyTextBoxes"></param>
        /// <remarks></remarks>
        public static void SetInputControlsHighlight(Control container, string className, bool onlyTextBoxes)
        {
            foreach (Control ctl in container.Controls)
            {
                if ((onlyTextBoxes && (ctl) is TextBox) || (ctl) is TextBox || (ctl) is DropDownList || (ctl) is ListBox ||
                    (ctl) is CheckBox || (ctl) is RadioButton || (ctl) is RadioButtonList || (ctl) is CheckBoxList)
                {
                    WebControl wctl = default(WebControl);
                    wctl = (WebControl) ctl;
                    wctl.Attributes.Add("onfocus", string.Format("this.className = '{0}';", className));
                    wctl.Attributes.Add("onblur", "this.className = '';");
                }
                else
                {
                    if ((ctl.Controls.Count > 0)) SetInputControlsHighlight(ctl, className, onlyTextBoxes);
                }
            }
        }

        #endregion

        #region "App Context"

        /// <summary>
        /// This is a core method to help get the physical path for the site and returns a 
        /// application variable from the web.config file.  It helps with the variations
        /// between local host and a delpoyed site.
        /// </summary>
        /// <value></value>
        /// <returns>Physical Path for Web Site</returns>
        /// <remarks></remarks>
        public static string ApplicationPath
        {
            get { return HttpContext.Current.Request.PhysicalApplicationPath; }
        }

        public static IPrincipal CurrentUser
        {
            get { return HttpContext.Current.User; }
        }

        public static string CurrentUserIP
        {
            get { return HttpContext.Current.Request.UserHostAddress; }
        }

        public static string CurrentUserName
        {
            get
            {
                string userName = string.Empty;
                if (CurrentUser.Identity.IsAuthenticated)
                {
                    userName = CurrentUser.Identity.Name;
                }
                return userName;
            }
        }

        public static string GetPhyscialPath(string vFolder)
        {
            return Path.Combine(ApplicationPath, vFolder);
        }

        private static void SetAppItem(string ItemName, string Value)
        {
            lock (HttpContext.Current.Application[ItemName])
            {
                HttpContext.Current.Application[ItemName] = Value;
            }
        }

        public static string GetApplicationItem(string ItemName)
        {
            if ((HttpContext.Current.Application[ItemName] == null))
            {
                SetAppItem(ItemName, string.Empty);
            }
            return HttpContext.Current.Application[ItemName].ToString();
        }

        public static void SetApplicationItem(string ItemName, string value)
        {
            SetAppItem(ItemName, value);
        }

        #endregion

        #region PhoneNumberFormat 

        /// <summary>
        /// Phone Number Format
        /// </summary>
        /// <remarks></remarks>
        public enum PhoneNumberFormat
        {
            Dashes = 2,
            Parenthises = 1,
            Periods = 3,
            Straight = 4
        }

        /// <summary>
        /// returns a Formatted Phone Number with Parenthises
        /// </summary>
        /// <param name="sPhoneNumber"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static string FormatPhoneNumber(string sPhoneNumber)
        {
            return FormatPhoneNumber(sPhoneNumber, PhoneNumberFormat.Parenthises);
        }

        /// <summary>
        /// Returns a Formatted Phone Number based on the PhoneNumberFormat
        /// </summary>
        /// <param name="sPhoneNumber"></param>
        /// <param name="pnf"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static string FormatPhoneNumber(string sPhoneNumber, PhoneNumberFormat pnf)
        {
            var rg = new Regex("^\\(?(\\d{3})\\)?[/ - .]?(\\d{3})[- .]?(\\d{4})$");

            switch (pnf)
            {
                case PhoneNumberFormat.Dashes:
                    return rg.Replace(sPhoneNumber, "$1-$2-$3");
                case PhoneNumberFormat.Parenthises:
                    return rg.Replace(sPhoneNumber, "($1) $2-$3");
                case PhoneNumberFormat.Periods:
                    return rg.Replace(sPhoneNumber, "$1.$2.$3");
                case PhoneNumberFormat.Straight:
                    return rg.Replace(sPhoneNumber, "$1$2$3");
            }


            return sPhoneNumber;
        }

        public static bool IsValidPhoneNumber(string sPhoneNumber)
        {
            return IsValidUSPhoneNumber(sPhoneNumber);
        }

        public static bool IsValidUSPhoneNumber(string sPhoneNumber)
        {
            RegexOptions options = RegexOptions.Multiline;

            MatchCollection matches = Regex.Matches(sPhoneNumber,
                                                    "^\\d{3}/\\d{3}-\\d{4}$^\\(\\d{3}\\)\\d{3}-\\d{4}$|^\\d{3}-\\d{3}-\\d{4}$|\\d{10}",
                                                    options);

            foreach (object found in matches)
            {
                return true;
            }


            return false;
        }

        public static string ParsePhoneNumber(string sPhoneNumber)
        {
            if (IsValidUSPhoneNumber(sPhoneNumber))
            {
                return sPhoneNumber.Replace("(", "").Replace(")", "").Replace("-", "");
            }
            return string.Empty;
        }
         #endregion
      
        public static int GetRandomNumber(int min, int max)
        {
            Random rand = new Random();
            return rand.Next(min, max);
        }

       

        private static readonly string[] _countries = new[]
                                                          {
                                                              "Afghanistan", "Albania", "Algeria", "American Samoa",
                                                              "Andorra", "Angola", "Anguilla", "Antarctica",
                                                              "Antigua And Barbuda", "Argentina", "Armenia", "Aruba",
                                                              "Australia", "Austria", "Azerbaijan", "Bahamas",
                                                              "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium",
                                                              "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia",
                                                              "Bosnia Hercegovina", "Botswana", "Bouvet Island",
                                                              "Brazil", "Brunei Darussalam", "Bulgaria",
                                                              "Burkina Faso", "Burundi", "Byelorussian SSR", "Cambodia",
                                                              "Cameroon", "Canada", "Cape Verde", "Cayman Islands",
                                                              "Central African Republic", "Chad", "Chile", "China",
                                                              "Christmas Island", "Cocos (Keeling) Islands", "Colombia",
                                                              "Comoros",
                                                              "Congo", "Cook Islands", "Costa Rica", "Cote D'Ivoire",
                                                              "Croatia", "Cuba", "Cyprus", "Czech Republic",
                                                              "Czechoslovakia", "Denmark", "Djibouti", "Dominica",
                                                              "Dominican Republic", "East Timor", "Ecuador", "Egypt",
                                                              "El Salvador", "England", "Equatorial Guinea", "Eritrea",
                                                              "Estonia", "Ethiopia", "Falkland Islands", "Faroe Islands"
                                                              , "Fiji", "Finland", "France", "Gabon", "Gambia",
                                                              "Georgia", "Germany", "Ghana",
                                                              "Gibraltar", "Great Britain", "Greece", "Greenland",
                                                              "Grenada", "Guadeloupe", "Guam", "Guatemela", "Guernsey",
                                                              "Guiana", "Guinea", "Guinea-Bissau", "Guyana", "Haiti",
                                                              "Heard Islands", "Honduras",
                                                              "Hong Kong", "Hungary", "Iceland", "India", "Indonesia",
                                                              "Iran", "Iraq", "Ireland", "Isle Of Man", "Israel",
                                                              "Italy", "Jamaica", "Japan", "Jersey", "Jordan",
                                                              "Kazakhstan",
                                                              "Kenya", "Kiribati", "Korea, South", "Korea, North",
                                                              "Kuwait", "Kyrgyzstan", "Lao People's Dem. Rep.", "Latvia"
                                                              , "Lebanon", "Lesotho", "Liberia", "Libya",
                                                              "Liechtenstein", "Lithuania", "Luxembourg", "Macau",
                                                              "Macedonia", "Madagascar", "Malawi", "Malaysia",
                                                              "Maldives", "Mali", "Malta", "Mariana Islands",
                                                              "Marshall Islands", "Martinique", "Mauritania",
                                                              "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldova",
                                                              "Monaco", "Mongolia", "Montserrat", "Morocco",
                                                              "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal",
                                                              "Netherlands", "Netherlands Antilles", "Neutral Zone",
                                                              "New Caledonia", "New Zealand", "Nicaragua", "Niger",
                                                              "Nigeria", "Niue", "Norfolk Island", "Northern Ireland",
                                                              "Norway", "Oman", "Pakistan", "Palau", "Panama",
                                                              "Papua New Guinea", "Paraguay", "Peru", "Philippines",
                                                              "Pitcairn", "Poland", "Polynesia",
                                                              "Portugal", "Puerto Rico", "Qatar", "Reunion", "Romania",
                                                              "Russian Federation", "Rwanda", "Saint Helena",
                                                              "Saint Kitts", "Saint Lucia", "Saint Pierre",
                                                              "Saint Vincent", "Samoa", "San Marino",
                                                              "Sao Tome and Principe", "Saudi Arabia",
                                                              "Scotland", "Senegal", "Seychelles", "Sierra Leone",
                                                              "Singapore", "Slovakia", "Slovenia", "Solomon Islands",
                                                              "Somalia", "South Africa", "South Georgia", "Spain",
                                                              "Sri Lanka", "Sudan", "Suriname", "Svalbard",
                                                              "Swaziland", "Sweden", "Switzerland",
                                                              "Syrian Arab Republic", "Taiwan", "Tajikista", "Tanzania",
                                                              "Thailand", "Togo", "Tokelau", "Tonga",
                                                              "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan"
                                                              , "Turks and Caicos Islands",
                                                              "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates",
                                                              "United Kingdom", "United States", "Uruguay", "Uzbekistan"
                                                              , "Vanuatu", "Vatican City State", "Venezuela", "Vietnam",
                                                              "Virgin Islands", "Wales", "Western Sahara", "Yemen",
                                                              "Yugoslavia", "Zaire", "Zambia", "Zimbabwe"
                                                          };



        public static StringCollection GetCountries()
        {
            var countries = new StringCollection();
            countries.AddRange(_countries);
            return countries;
        }

        public static SortedList GetCountries(bool insertEmpty)
        {
            var countries = new SortedList();
            if (insertEmpty)
            {
                countries.Add("", "Please select one...");
            }
            foreach (string country in _countries)
            {
                countries.Add(country, country);
            }
            return countries;
        }

        public static DirectoryInfo MakeDirectory(string vDirectoryPath)
        {
            if (Directory.Exists(vDirectoryPath))
            {
                return new DirectoryInfo(vDirectoryPath);
            }
            return Directory.CreateDirectory(vDirectoryPath);
        }

    }
}
